package cn.kgc.jinxin.clothesstore.service.impl;

import cn.kgc.jinxin.clothesstore.dao.BaseDao;
import cn.kgc.jinxin.clothesstore.dao.GoodsDao;
import cn.kgc.jinxin.clothesstore.dao.OrderDao;
import cn.kgc.jinxin.clothesstore.dao.OrderDetailDao;
import cn.kgc.jinxin.clothesstore.dao.impl.GoodsDaoImpl;
import cn.kgc.jinxin.clothesstore.dao.impl.OrderDaoImpl;
import cn.kgc.jinxin.clothesstore.dao.impl.OrderDetailDaoImpl;
import cn.kgc.jinxin.clothesstore.entity.Order;
import cn.kgc.jinxin.clothesstore.entity.OrderDetail;
import cn.kgc.jinxin.clothesstore.service.OrderService;

import java.sql.*;
import java.util.Map;
public class OrderServiceImpl implements OrderService {
	private OrderDao orderDao = new OrderDaoImpl();
	private OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
	private GoodsDao goodsDao = new GoodsDaoImpl();

	@Override
	public void add(Order order) throws Exception {
		Connection connection = null;
		try {
			connection = BaseDao.getConnection();
			connection.setAutoCommit(false);
			this.orderDao.insert(order, connection);
			for(OrderDetail orderDetail:order.getOrderDetailList()) {
				this.orderDetailDao.insert(orderDetail, connection);
				this.goodsDao.updateStock(orderDetail.getGoods().getGoodsId(), orderDetail.getOrderNum(), connection);
			}
			this.orderDao.update(order.getOrderId(), order.getOrderTotalPrice(), connection);
			connection.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			connection.rollback();
			throw e;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			connection.setAutoCommit(true);
			BaseDao.close(connection, null, null);
		}
	}

	@Override
	public Map<String, Double> findTotalPriceByUser() throws Exception {
		return this.orderDao.selectTotalPriceByUser();
	}
}
